package com.blacktea.behavioralpatterns.strategypattern;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;

/**
 * @description: 支付上下文
 * @author: black tea
 * @date: 2023/3/26 18:00
 */
@Component
@RequiredArgsConstructor
public class PayContext {

    private final Map<String, PayStrategy> payStrategyMap;

    private PayStrategy payStrategy;

    public void setPayStrategy(String payType) {
        Optional<PayStrategy> payStrategyOptional = getPayStrategyByKey(payType);
        this.payStrategy = payStrategyOptional
                .orElseThrow(()-> ExceptionUtil.wrapRuntime("找不到具体类型为【" + payType + "】的支付策略类"));
    }

    public void setPayStrategy(Class<? extends PayStrategy> cls) {
        String simpleName = cls.getSimpleName();
        String mapKey = StrUtil.lowerFirst(simpleName);
        Optional<PayStrategy> payStrategyOptional = getPayStrategyByKey(mapKey);
        this.payStrategy = payStrategyOptional
                .orElseThrow(()-> ExceptionUtil.wrapRuntime("找不到具体的【" + simpleName + "】支付策略类"));
    }

    private Optional<PayStrategy> getPayStrategyByKey(String mapKey){
        return Optional.ofNullable(payStrategyMap.get(mapKey));
    }

    public void pay(BigDecimal amount){
        payStrategy.pay(amount);
    }

}
